package cn.bud.msgbus.server.server.subscribe;

import cn.hutool.json.JSONObject;
import com.zl9c.general.bus.bean.MsgBody;
import com.zl9c.general.bus.bean.Subscriber;
import com.zl9c.general.utils.Zl9cApplicationContext;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

/**
 * Subscribtion
 *
 * @author hxj
 * @version 1.0
 * @description
 * @date 2024-06-19 14:14
 */
@Slf4j
@Data
@EqualsAndHashCode(callSuper = true)
public class HttpSubscriber extends Subscriber {

    private String url;
    private RestTemplate restTemplate;

    @Override
    public String name() {
        return url;
    }

    @Override
    public void sendMsg(MsgBody msg) {
        if (!topicSet().contains(msg.getTopic())) {
            return;
        }
        if (isTimeUnEffect(msg.getTopic())) {
            return;
        }
        JSONObject jsonObject = msg.jsonObj();
        httpPost(jsonObject.toJSONString(0), 0);
    }

    private void httpPost(String msgJsonStr, int retryTimes) {
        if (restTemplate == null) {
             restTemplate = Zl9cApplicationContext.getBeanByClazz(RestTemplate.class);
        }
        if (restTemplate == null) {
            log.warn("http订阅推送异常，未找到restTemplate实例");
            return;
        }
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> httpEntity = new HttpEntity<>(msgJsonStr,headers);
            ResponseEntity<Object> rsp = restTemplate.postForEntity(url, httpEntity, Object.class);
            if (rsp.getStatusCode() == HttpStatus.OK) {
                log.debug("http订阅推送：url={}，推送的数据：{}",
                        url, msgJsonStr);
            }
        }catch (Exception e) {
            retryTimes++;
            log.warn("http订阅推送异常：url={}，第{}次推送，推送的数据：{}，异常提示：{}",
                    url, retryTimes, msgJsonStr, e.getMessage());
            if (retryTimes < 3) {
                httpPost(msgJsonStr, retryTimes);
            }
            throw e;
        }
    }

    @Override
    public String toString() {
        return "HttpSubscriber{" +
                "url='" + url + '\'' +
                ", restTemplate=" + restTemplate +
                ", topics=" + topics +
                '}';
    }
}
